import { readFileSync, writeFileSync } from "fs";
import fs from 'fs';
import path from 'path';

const getReqs = (par) => {
    if (!par) {
        console.log("ERROR when -r");
        return;
    }
    let initModelName = par.split(/[\\|/]/).pop().split(".")[0].replace("CNEN", "");
    getFretishes(textParse(par), initModelName);
}

/*
[
    {
        "id": "", 
        "content": "",
        "comment": "",  
        "reqCN": "",
        "reqEN": ""
    }
]
*/
let textParse = (filePath) => {
    let fretishes = [];
    if (filePath.endsWith(".txt")) {
        let text = readFileSync(filePath, "utf8");
        let lines = text.split("\r\n");
        
        for (let line of lines) {
            if (line.trim() === "") continue; // Skip empty lines
            let parts = line.split(": ");
            let id = parts[0];
            let content = parts[1];
            fretishes.push({ id, content });
        }
    } else {
        fretishes = inputByFile(filePath, 1);
    }
    
    if (!fretishes || fretishes.length == 0) {
        throw new Error(`Failed to parse fretishes from file: ${filePath}`);
    }
    return fretishes;
}

let getFretishes = (fretishes, name) => {
    // console.log(fretishes);
    fetch('http://101.132.154.120:3030/frelink/batch', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        fretishes: fretishes
    })
    }).then(response => response.json())
    .then(data => {
        writeFileSync(`./public/out_json/${name}.json`, JSON.stringify(formatRes(data), null, 2));
        // console.log(JSON.stringify(formatRes(data), null, 2));
    })
    .catch(error => console.error('Error:', error));
}

let formatRes = (res) => {
    if (!Array.isArray(res)) res = res.res;
    if (!res) throw new Error(`Errors when parsing fretishes: ${res.errors}`);
    for (let item of res) {
        if (item.errors != "") {
            throw new Error(`Errors in ${item.reqid}: ${item.errors}`);
        }
    }
    // console.log("Fretishes processed successfully.");
    return res;
}

let inputByFile = (file_name, type) => {
    if(!fs.existsSync(file_name)){
        console.warn(`WARN: File ${file_name} does not exist.`);
        return undefined;
    }
    
    if (type === 1) {
        return JSON.parse(fs.readFileSync(path.resolve(file_name), 'utf-8'));
    }
    return undefined;
}

export default getReqs;